package com.xuecheng.manage_cms_client.service.impl;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.CmsSite;
import com.xuecheng.manage_cms_client.dao.CmsSiteRepository;
import com.xuecheng.manage_cms_client.dao.PageRepository;
import com.xuecheng.manage_cms_client.service.CmsPageService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
@Service
public class CmsPageServiceImpl implements CmsPageService {
    public static final Logger LOGGER = LoggerFactory.getLogger(CmsPageServiceImpl.class);

    @Autowired
    PageRepository pageRepository;

    @Autowired
    GridFsTemplate gridFsTemplate;

    @Autowired
    GridFSBucket gridFSBucket;

    @Autowired
    CmsSiteRepository cmsSiteRepository;

    @Override
    public void savePageToServerPath(String pageId) {
        //查询页面信息
        CmsPage cmsPage = this.getCmsPageById(pageId);
        if(null == cmsPage){
            LOGGER.error("CmsPageServiceImpl savePageToServerPath cmsPage is null,pageId:{}",pageId);
        }
        //获取htmlfileid
        String htmlFileId = cmsPage.getHtmlFileId();
        //根据htmlfileid从gridfs下载文件到页面的物理路径
        InputStream inputStream = getFileByHtmlFileId(htmlFileId);
        if(null == inputStream){
            LOGGER.error("CmsPageServiceImpl savePageToServerPath inputstream is null,pageId:{}",pageId);
        }
        //获取站点信息
        CmsSite cmsSite = getCmsSiteBySiteId(cmsPage.getSiteId());

        //获取物理全路径
        String pagePath = cmsSite.getSitePhysicalPath() + cmsPage.getPagePhysicalPath() + cmsPage.getPageName() + ".html";
        FileOutputStream fileOutputStream = null;
        //下载文件到物理路径
        try {
            fileOutputStream = new FileOutputStream(new File(pagePath));
            IOUtils.copy(inputStream,fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private CmsSite getCmsSiteBySiteId(String siteId) {
        Optional<CmsSite> optional = cmsSiteRepository.findById(siteId);
        if(optional.isPresent()){
            CmsSite cmsSite = optional.get();
            return cmsSite;
        }
        return null;
    }

    private InputStream getFileByHtmlFileId(String htmlFileId) {
        //获取文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(htmlFileId)));
        //打开下载流
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //获取gridfsresource
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        //获取下载流
        InputStream inputStream = null;
        try {
            inputStream = gridFsResource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }


    public CmsPage getCmsPageById(String pageId){
        Optional<CmsPage> optional = pageRepository.findById(pageId);
        if(optional.isPresent()){
            CmsPage cmsPage = optional.get();
            return cmsPage;
        }
        return null;
    }
}
